package net.atomarrow.boot;

import net.atomarrow.annotation.Inject;
import net.atomarrow.configs.Config;
import net.atomarrow.configs.DbConfig;
import net.atomarrow.configs.scan.ConfigScanner;
import net.atomarrow.dispatcher.FilterDispatcher;
import net.atomarrow.inits.InitLoadProcessor;
import net.atomarrow.ioc.ApplicationContext;
import net.atomarrow.plugins.PluginManager;

import javax.servlet.*;
import javax.servlet.annotation.WebListener;
import java.util.EnumSet;

/**
 * @author Boolone
 * @date 2020/2/12
 */
@WebListener
public class AppStarter implements ServletContextListener {
    @Inject
    private ConfigScanner configScanner;
    @Inject
    private DbConfig dbConfig;
    @Inject
    private PluginManager pluginManager;

    @Inject
    private InitLoadProcessor initLoadProcessor;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        ApplicationContext.inject(this);
        configScanner.scan();
        ServletContext servletContext = event.getServletContext();
        initLoadProcessor.execute(servletContext);
        pluginManager.startPlugins();
//        //如果开发环境，开启检测文件改动
//        if(ApplicationContext.get(Config.class).configHotDeploy()){
//            System.out.println(servletContext.getRealPath("/WEB-INF/classes"));
//            new ClassAlterationMonitor().start(servletContext.getRealPath("/WEB-INF/classes"));
//        }

        registFilter(servletContext);
        System.out.println("The server has started successfully");
    }

    /**
     * 注册Filter
     */
    private void registFilter(ServletContext sc) {
        Config config = ApplicationContext.get(Config.class);
        Class filter = FilterDispatcher.class;
        FilterRegistration.Dynamic dynamic = sc.addFilter(filter.getSimpleName(), filter.getCanonicalName());
        dynamic.addMappingForUrlPatterns(
                EnumSet.of(DispatcherType.REQUEST, DispatcherType.INCLUDE, DispatcherType.FORWARD, DispatcherType.ERROR)
                , true, config.configFilterMapping());
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        pluginManager.stopPlugins();
        dbConfig.closeDataSourse();
    }
}
